package com.ruoyi.netty.metrics;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 监控指标服务
 */
@Service
@Slf4j
@ConditionalOnBean(MeterRegistry.class)
public class MetricsService {

    private final Counter activeConnectionsCounter;
    private final Counter writeErrorsCounter;
    private final Timer writeLatencyTimer;

    public MetricsService(MeterRegistry registry) {
        // PLC连接数指标
        this.activeConnectionsCounter = Counter.builder("plc_connections_active")
                .description("Number of active PLC connections")
                .register(registry);

        // 写入错误计数器
        this.writeErrorsCounter = Counter.builder("influxdb_write_errors")
                .description("Number of InfluxDB write errors")
                .register(registry);

        // 写入延迟计时器
        this.writeLatencyTimer = Timer.builder("influxdb_write_latency")
                .description("InfluxDB write latency")
                .register(registry);
    }

    /**
     * 增加活动连接数
     */
    public void incrementActiveConnections() {
        activeConnectionsCounter.increment();
    }

    /**
     * 减少活动连接数
     */
    public void decrementActiveConnections() {
        activeConnectionsCounter.increment(-1);
    }

    /**
     * 增加写入错误计数
     */
    public void incrementWriteErrors() {
        writeErrorsCounter.increment();
    }

    /**
     * 记录写入延迟
     *
     * @param latencyMs 延迟时间(毫秒)
     */
    public void recordWriteLatency(long latencyMs) {
        writeLatencyTimer.record(latencyMs, TimeUnit.MILLISECONDS);
    }
} 